package cn.tedu.user.service;

import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jt.common.pojo.User;
import com.jt.common.utils.MapperUtil;

import cn.tedu.user.mapper.UserMapper;
import redis.clients.jedis.Jedis;

@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;
	public Boolean checkUserName(String userName) {
		int result=userMapper
				.selectUserCountByUserName(userName);
		//result不是1就是0
		return result==1;
	}
	public void saveUser(User user) {
		//封装userId
		String userId=UUID.randomUUID().toString();
		user.setUserId(userId);
		//加密password
		String md5Password=DigestUtils.md5Hex(user.getUserPassword());
		System.out.println("密码密文:"+md5Password);
		user.setUserPassword(md5Password);
		//userType 数据库在接收到null 默认值0
		userMapper.insertUser(user);
	}
	public String doLogin(User user) {
		/*1.登录校验,到数据库利用username password加密查询数据
		 *2.判断返回结果是否为空
		 *	2.1为空;登录失败返回一个""的ticket
		 *	2.2不为空;生成ticket 序列化查询的user对象
		 *		创建jedis对象将ticket userJson set超时时间
		 *		放到redis中 2小时
		 *3.将ticket返回
		 */
		//对user参数对象做密码的加密处理
		user.setUserPassword(DigestUtils.md5Hex
				(user.getUserPassword()));
		User exist=userMapper
				.selectUserByUserNameAndPassword(user);
		//准备一个返回的ticket 默认值是""/null
		String ticket="";
		//判断exist是否为空
		if(exist==null){
			//登录失败
			return ticket;
		}else{//登录成功
			//构造ticket的值
			ticket="EM_TICKET"+
			System.currentTimeMillis()+exist.getUserId();
			Jedis jedis=new Jedis("10.42.149.141",6380);
			//exist user的序列化过程
			try{
				String userJson=
					MapperUtil.MP.writeValueAsString(exist);
				jedis.setex(ticket, 60*60*2, userJson);
			//将数据存储到redis中,关闭连接
				return ticket;
			}catch(Exception e){
				e.printStackTrace();
				return "";
			}finally{
				jedis.close();
			}
		}
		
	}
	public String checkLoginUserData(String ticket) {
		Jedis jedis=new Jedis("10.42.149.141",6380);
		try{
			String userJson=jedis.get(ticket);
			return userJson;
		}catch(Exception e){
			e.printStackTrace();
			return "";
		}finally{
			jedis.close();
		}
		
	}

	
	
	
	
	
	
	
	
	
}
